﻿using System;
using System.Threading;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        // 创建 CancellationTokenSource 对象
        CancellationTokenSource cts = new CancellationTokenSource();

        // 获取 CancellationToken
        CancellationToken token = cts.Token;

        // 启动一个可取消的 Task
        Task task = Task.Run(() => DoWork(token), token);

        try
        {
            // 模拟一段时间后取消任务
            await Task.Delay(2000);
            cts.Cancel();

            // 等待任务完成
            await task;
        }
        catch (OperationCanceledException)
        {
            Console.WriteLine("任务已取消。");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"发生错误: {ex.Message}");
        }
        finally
        {
            cts.Dispose();
        }
    }

    static void DoWork(CancellationToken cancellationToken)
    {
        while (true)
        {
            // 检查取消请求
            if (cancellationToken.IsCancellationRequested)
            {
                // 抛出 OperationCanceledException 以表明任务已取消
                cancellationToken.ThrowIfCancellationRequested();
            }

            Console.WriteLine("工作进行中...");
            Thread.Sleep(500);
        }
    }
}